package imageEditor.utility;

import java.awt.Image;
import java.awt.Toolkit;
import java.awt.image.BufferedImage;
import java.awt.image.MemoryImageSource;
import java.awt.image.PixelGrabber;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.HashMap;
import java.util.Set;

import javax.imageio.ImageIO;


public class ImageDatabase {
	
	private HashMap<Integer, int[]> mapImages, mapSizes;
	
	
	public ImageDatabase(String path){
		if(path==null){
			mapImages=new HashMap<Integer, int[]>();
			mapSizes=new HashMap<Integer, int[]>();
		} else{
			try {load(path);} 
			catch (Exception e) {
				mapImages=new HashMap<Integer, int[]>();
				mapSizes=new HashMap<Integer, int[]>();
				e.printStackTrace();
			}
		}
	}
	
	
	public void addImage(String path, int id) throws IOException, InterruptedException{	
		addImage(new File(path),id);
	}
	
	public void addImage(File file, int id) throws IOException, InterruptedException{	
		loadImageFromFile(file,id);
	}
	
	public void save(String name) throws IOException{
		FileOutputStream fos = new FileOutputStream(name);
		ObjectOutputStream oos = new ObjectOutputStream(fos);
		oos.writeObject(mapImages);
		oos.writeObject(mapSizes);
		oos.close();
	}
	
	public void load(String name) throws IOException, ClassNotFoundException{
		FileInputStream fis = new FileInputStream(name);
		ObjectInputStream iis = new ObjectInputStream(fis);
		mapImages = (HashMap<Integer, int[]>)iis.readObject();
		mapSizes = (HashMap<Integer, int[]>)iis.readObject();
		iis.close();
	}
	
	private void loadImageFromFile(File file, int id) throws IOException, InterruptedException{
		BufferedImage loadImg = ImageIO.read(file);
		int width=loadImg.getWidth(), height=loadImg.getHeight();
		
		mapImages.put(id,getArrayFromImage(loadImg,width, height));  
		mapSizes.put(id, new int[]{width,height});
	}
	
	private static int[] getArrayFromImage(Image img, int width, int height) throws InterruptedException {
		int[] pixels = new int[width * height];
		PixelGrabber pg = new PixelGrabber(img, 0, 0, width, height, pixels,0, width);
		pg.grabPixels();
		return pixels;
	}
	 
	public static Image getImageFromArray(int[] pixels, int width, int height) {
		MemoryImageSource mis = new MemoryImageSource(width, height, pixels,0, width);
		Toolkit tk = Toolkit.getDefaultToolkit();
		return tk.createImage(mis);
	}
	
	public Image getMapImge(int id){
		int[] sizes=mapSizes.get(id);
		return getImageFromArray(getMap(id), sizes[0], sizes[1]);
	}
	
	public int[] getMap(int id){
		return mapImages.get(id);
	}
	
	public Set<Integer> getId(){
		return mapImages.keySet();
	}


	public Point2d getSize(int id) {
		return new Point2d(mapSizes.get(id));
	}


	public void addImage(int[] value, int key, int w, int h) {
		mapImages.put(key, value);
		mapSizes.put(key, new int[]{w,h});
	}

}
